package org.nbict.iot.task.seriestime;

import com.alibaba.fastjson.JSONObject;
import org.apache.storm.trident.operation.FlatMapFunction;
import org.apache.storm.trident.tuple.TridentTuple;
import org.apache.storm.tuple.Values;
import org.nbict.iot.protocol.util.BinaryUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by songseven on 18/7/3.
 */
public class SeriestimeResolver implements FlatMapFunction {

    private static final String[] tags = {"01", "02", "03", "04", "05", "06",
            "07", "08", "09"};

    @Override
    public Iterable<Values> execute(TridentTuple tuple) {
        //"platform_id", "car_vin", "action","timestamp", "upload"

        List<Values> valuesList = new ArrayList<>();
        //String platform_id = tuple.getString(0);
        String vin = tuple.getString(1);
        Long timestamp = tuple.getLong(3);
        JSONObject upload = (JSONObject) tuple.get(4); //info
        boolean isRun = false; //是否启动
        //计算车辆状态，屏蔽掉熄火状态下定位信息
        JSONObject t = (JSONObject) upload.get("01");
        //定位信息
        JSONObject g = (JSONObject) upload.get("05");
        if (t != null) {
            isRun = t.get("status").equals("01");
        }
        for (int i = 0; i < 9; i++) {
            if (upload.get(tags[i]) != null && g != null ) { //定位信息有效
                // vin, timestamp, tag, 01-09, isRun
                String coordState = g.getString("coord_state"); //定位状态
                if (coordState != null) {
                    int stateInt = Integer.valueOf(coordState);
                    if (!BinaryUtil.checkBit(stateInt, 1)) { //过滤无效定位 2018-8-3
                        valuesList.add(new Values(vin, timestamp, tags[i], upload.get
                                (tags[i]), isRun, g));
                    }
                }
            }
        }
        return valuesList;
    }
}
